<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */

class Login extends CF_Controller {
	function __construct() {
		global $Lang, $UI;
		$this->title = $Lang->getFormattedKey("global.user.login");
		$this->desc = "";
	}
	
	function _write_login_log($uid, $status) {
		global $DB;
		return $DB->Driver->insert_query(
			"acp_logins",
			array(
				"status" => $status,
				"ip" => $_SERVER['REMOTE_ADDR'],
				"uid" => intval($uid)
			)
		);
	}
	
	function Index() {
		global $Views, $Models, $DB, $Encryption, $UI, $Lang, $Hooks;
		if(isset($_SESSION["cf_uid"], $_SESSION["cf_acp_accessed"])) {
			$Views->Load("already_logged_in");
		}
		else {
			if(isset($_POST['username'], $_POST['password'])) {
				$Users_model = $Models->Load("users_model");
				$rt = $Users_model->retrieve("singleuname", $_POST['username']);
				if($rt) {
					if($rt['password'] === $Encryption->Encrypt($_POST['password'])) {
						$Groups_model = $Models->Load("groups_model");
						$g = $Groups_model->retrieve("singleid", $rt['group']);
						//var_dump($g);
						if(!$g or $g['is_admin'] != "1") {
							$Hooks->run_hooks("acp_login_failed_attempt_before");
							$UI->message("Sorry, you do not have administrative permissions!", "error");
							$Views->Load("login_form");
							// Log this guy, he *is* suspicious
							$Hooks->run_hooks("acp_login_log_failed_attempt_before");
							$this->_write_login_log($rt['id'], "Failed Login Attempt (No access)");
							if(isset($_SESSION["cf_uid"])) unset($_SESSION["cf_uid"]); // Get him out of here...
						}
						else {
							$Hooks->run_hooks("acp_login_success_attempt_before");
							$UI->message("Login complete - redirecting you to the administration panel", "success");
							$UI->redirect("/admin.php");
							if(!isset($_SESSION["cf_uid"])) $_SESSION["cf_uid"] = $rt['id'];
							if(!isset($_SESSION["cf_passhash"])) $_SESSION["cf_passhash"] = $rt['password'];
							if(!isset($_SESSION["cf_acp_accessed"])) $_SESSION["cf_acp_accessed"] = true;
							$Hooks->run_hooks("acp_login_log_success_attempt_before");
							$this->_write_login_log($rt['id'], "Successful Login attempt");
						}
					}
					else {
						// Password does not match
						$UI->message($Lang->getFormattedKey("global.user.login.fail.pw"), "error");
						$Views->Load("login_form");
						$this->_write_login_log($rt['id'], "Failed Login Attempt (Password wrong)");
						if(isset($_SESSION["cf_uid"])) unset($_SESSION["cf_uid"]); // Get him out of here...
					}
				}
				else{
					// Username not found
					$UI->message($Lang->getFormattedKey("global.user.login.fail.un"), "error");
					$Views->Load("login_form");
					// FIXME: Log?
				}
			}
			else {
				// Show form :)
				$Views->Load("login_form");
			}
		}
	}
}
